<template>
	<view>
		<map id="map" :longitude="longitude" :latitude="latitude" scale="13" min-scale='10' max-scale='16' :markers="markers"
			:polygons='polygons' :circles='circles' :controls='controls' @markertap='clickMarker'
			style="width: 100%; height: 100vh;">
		</map>
	</view>
	<view class="btn">
		<button @click="() => { this.show = true }">+</button>
	</view>
	<view class="start"> {{ startGrazingNum }} </view>
	<!-- <view class="closeWarn" @click="closealert"> 关闭警告 </view> -->
	<view class="popup">
		<u-popup :show="show" mode="left" @close="close" @open="open">
			<view style="width: 60vw;height: 100vh;">
				<!-- u-tabs点击之后下面的内容会抖动 -->
				<u-tabs
					:list="[{ name: '危险', value: 'error' }, { name: '警告', value: 'warn' }, { name: '安全', value: 'safe' }, { name: '全部', value: 'all' },]"
					:scrollable='false' lineColor="orange" lineHeight='5' @change="updCurrentDisplayType"></u-tabs>
				<u-button @tap="setNum" type="primary" text="更新羊圈中羊的数量"></u-button>
				<u-button type="warning" text="修改围栏" @tap="updateFencing"></u-button>
				<u-button type="success" :plain="page != 0 ? true : false" @tap="() => { this.page = 0 }"> 所有羊群 <text
						v-show="quantity('error', 0)" style="color:red">({{ quantity('error', 0) }})</text>
					<text v-show="quantity('warn', 0)" style="color:orange">({{ quantity('warn', 0) }})</text>
					<text v-show="quantity('safe', 0)" style="color:green">({{ quantity('safe', 0) }})</text>
					<text v-show="quantity('all', 0)" style="color:blue">({{ quantity('all', 0) }})</text>
				</u-button>
				<u-button v-for="(item) in PageCount" type="primary" :plain="item == page ? false : true"
					@click='() => { this.page = item }'> 第{{ item }}群羊 <text v-show="quantity('error', item)" style="color:red">({{
						quantity('error', item) }})</text>
					<text v-show="quantity('warn', item)" style="color:orange">({{ quantity('warn', item) }})</text>
					<text v-show="quantity('safe', item)" style="color:green">({{ quantity('safe', item) }})</text>
					<text v-show="quantity('all', item) != num" style="color:blue">({{ quantity('all', item) }})</text>
				</u-button>
			</view>
		</u-popup>
	</view>
	<view>
		<u-modal :show="navShow" :closeOnClickOverlay="true" @confirm="navNow" @cancel="navShow = false"
			@close='navShow = false' confirmText='立即导航' cancelText='取消导航' :showCancelButton='true'>
			<view class="slot-content">
				<image :src="navItem?.img"></image>
				<text :style="{color:navItem.color}" class="text">{{navItem.id}}</text>
			</view>
		</u-modal>
	</view>
	<u-popup :show="showalert" mode="center" @close="closealert" @open="openalert">
		<view class="alert">
			<view style="padding-left: 5px;padding-top:5px;margin-bottom: 10px;"><text style="font-weight: 1000;">出圈羊数</text>:<text style="color:red">{{ quantity('error', 0) }}</text>/{{ quantity('all', 0) }}</view>
			<scroll-view scroll-y="true" class="scroll-Y">
				<view style="width: 100%;display: flex;justify-content: space-around;">
					<text>羊羊ID</text>
					<text style="margin-right: 10px;">距离</text>
					<text>操作</text>
				</view>
				<view class="modalList">
					<view class="listItem" v-for="item in errlist" :key="item._id">
						<view style="display: flex;justify-content: space-around;flex-wrap: wrap;text-align: center;line-height: 50px;">
							<text>{{ item.id }}号</text>
							<text>{{ item.dikm < 1 ? item.dikm * 100 + 'm' : item.dikm + 'km' }}</text>
							<text @click="goNav(item)">立即跳转</text>
						</view>
					</view>
					
				</view>
			</scroll-view>
		</view>
		<u-button type="primary" @tap="closealert">关闭警告</u-button>
	</u-popup>
</template>

<script>
import QQMapWX from '../../common/qqmap-wx-jssdk.js'
import request from '../../utils/request.js'
import {getlistcyp,setSecureNum,getSecureNum,getEachGroupNum,getAllNum} from '../../api'

let flattenDeep = (arr)=>{
	let Arr = []
    
	if(Array.isArray(arr) && arr.length){
		arr.forEach(item=>{
            if(typeof item == 'object'){
			if(Array.isArray(item)){
				Arr.push(...item)
			}}
		})
	}
	return Arr
}

let allmarkers = []//所有的羊群
let safemarkers = []//安全的羊群
let warnmarkers = []//警告的羊群
let errormarkers = []//危险的羊群
export default {
	data() {
		return {
			data: [],
			latitude: 43.635,
			longitude: 87.495,
			polyline: [], // 路线
			markers: [],
			circles: [],
			controls: [],
			polygons: [], // 多边形
			qqmapsdk: null,
			show: false, //是否展示弹出框
			ifall: 0, //是否现实所有羊
			PageCount: 0, //总页码
			page: 0, //当前页码
			vertex: [], //顶点存放位置
			warn: [],//警告顶点位置
			safe: [],//安全顶点位置
			music: null,
			startGrazingNum: 0,//开始放牧时羊群的数量
			currentDisplayType: 'error',//当前显示的羊的类型
			num: 0,//每群 羊的数量
			dateTime: new Date().getTime(),//判断是否大于30s
			navShow: false,//立即导航的是否展示
			navItem: {},//要展示的羊的信息
			showalert: false,// 是否展示警告弹窗
			errlist:[],//出圈羊的出圈距离
		}
	},
	onLaunch() {
		this.qqmapsdk = new QQMapWX({
			key: 'M5JBZ-XEZCJ-6SPFB-DH4E5-QFCS7-FCBTQ'
		});
		uni.onLocationChange(function (res) {
			console.log('纬度：' + res.latitude);
			console.log('经度：' + res.longitude);
		});
		uni.onLocationChangeError((e) => {
		})
	},
	onLoad() {
		this.qqmapsdk = new QQMapWX({
			key: 'M5JBZ-XEZCJ-6SPFB-DH4E5-QFCS7-FCBTQ'
		});
		// 三区
		getlistcyp().then((res) => {
			this.vertex = res.data.fence
			this.warn = res.data.polygons
			this.safe = res.data.polygonstwo
		}).finally(() => {
			this.polygons = [{
				points: [...this.vertex],
				fillColor: "#F56C6C", // 填充颜色
				strokeColor: "#F56C6C", // 描边颜色
				strokeWidth: 2, // 描边宽度
				zIndex: 3 //层级
			}, {
				points: [...this.warn],
				fillColor: "#E6A23C", // 填充颜色
				strokeColor: "#E6A23C", // 描边颜色
				strokeWidth: 2, // 描边宽度
				zIndex: 4 //层级
			},
			{
				points: [...this.safe],
				fillColor: "#67C23A", // 填充颜色
				strokeColor: "#67C23A", // 描边颜色
				strokeWidth: 2, // 描边宽度
				zIndex: 4 //层级
			},]
			// 获取羊圈中的羊的数量
			this.getNum()
			//危险区触发警告
			this.Inquire()
		})
	},
	onUnload: function () {
		this.closealert()
		this.showalert = false
	},
	computed: {
		// 双倍num
		quantity() {
			return (type, page) => {
				switch (type) {
					case 'error':
						return page ? errormarkers[page]?.length : flattenDeep(errormarkers)?.length
					case 'warn':
						return page ? warnmarkers[page]?.length : flattenDeep(warnmarkers)?.length
					case 'safe':
						return page ? safemarkers[page]?.length : flattenDeep(safemarkers)?.length
					case 'all':
						return page ? allmarkers[page]?.length + safemarkers[page]?.length : flattenDeep(allmarkers)?.length + flattenDeep(safemarkers)?.length
				}
			}
		}
	},
	methods: {
		goNav(item){
			this.navItem = item
			this.navNow()
		},
		// 修改当前显示的羊的类型
		updCurrentDisplayType(e) {
			this.currentDisplayType = e.value
		},
		// 获取当前点击的羊的id，通过id找到羊的所有信息
		clickMarker(e) {
			let error, warn, safe, emergent
			emergent = flattenDeep(errormarkers).find((item) => {
				if (item?.id == e.markerId) {
					return item
				}
			})
			error = flattenDeep(warnmarkers).find((item) => {
				if (item?.id == e.markerId) {
					return item
				}
			})
			warn = flattenDeep(safemarkers).find((item) => {
				if (item?.id == e.markerId) {
					return item
				}
			})
			safe = flattenDeep(allmarkers).find((item) => {
				if (item?.id == e.markerId) {
					return item
				}
			})
			this.navItem = emergent?._id ? { color:"white",img: '../../static/emergent.png', ...emergent } : error?._id ? {color:"red", img: '../../static/error.png', ...error } : warn?._id ? { color:"orange",img: '../../static/warn.png', ...warn } : safe?._id ? { color:"green", img: '../../static/safe.png', ...safe } : {}
			if (this.navItem.img) {
				this.navShow = true
			}

		},
		// 立即导航
		navNow() {
			this.navShow = false
			this.closealert()
			// 跳转导航
			uni.navigateTo({
				url: '/pages/driverHome/driverHome?id=' + this.navItem._id
			})
		},
		// 更新羊圈中的羊的数量
		async setNum() {
			// await request('/zq/InquireSecurePage')
			await setSecureNum()
			this.getNum()
		},
		// 获取羊圈中的羊的数量
		getNum() {
			// request('/zq/setNum').then(res => {
			// 	this.startGrazingNum = res.data.num
			// })
			getSecureNum().then(res => {
				this.startGrazingNum = res.data.num
			})
		},
		//打开作何弹框
		open() {
		},
		//关闭左侧弹框
		close() {
			this.show = false
			if (new Date().getTime() - 1500000 > this.dateTime) {
				this.getlist()
				this.dateTime = new Date().getTime()
			} else {
				this.updShow()
			}
		},
		// 获取危险、警告、安全和剩余的羊
		getlist(array) {
			// 获取最新数据
			let _safemarkers = []
			let _warnmarkers = []
			let _errormarkers = []
			let _allmarkers = []
			for (let i = 1; i <= this.PageCount; i++) {
				getEachGroupNum(array,i).then(res => {
				// request('/zq/InquirePage?page=' + i, { data: array }, 'POST').then(res => {

					_safemarkers[i] = [...res.data.safeList]
					_warnmarkers[i] = [...res.data.warnList]
					_errormarkers[i] = [...res.data.errorList]
					_allmarkers[i] = [...res.data.list]

				}).catch(error => {
					console.error(error);
				}).finally(() => {
					if (_allmarkers.length == 7) {
						safemarkers = _safemarkers
						warnmarkers = _warnmarkers
						errormarkers = _errormarkers
						allmarkers = _allmarkers
						this.updShow()
					}
				})
			}

		},
		updShow() {
			// 判断所有的请求是否都以及完成
			if(flattenDeep(errormarkers).length && this.thime==null){
				this.ScanAudio()
				this.showalert = true
				flattenDeep(errormarkers).forEach(item=>{
					this.getPathing(item)
				})
			}
			// 判断全部羊群还是某一羊群
			if (this.page == 0) {
				// 将数据放入markers
				switch (this.currentDisplayType) {
					case 'error':
						this.markers = [...flattenDeep(errormarkers)]
						return
					case 'warn':
						this.markers = [...flattenDeep(warnmarkers)]
						return
					case 'safe':
						this.markers = [...flattenDeep(safemarkers)]
						return
					case 'all':
						this.markers = [...flattenDeep(allmarkers), ...flattenDeep(errormarkers), ...flattenDeep(warnmarkers), ...flattenDeep(safemarkers)]
						return
				}
			} else {
				// 将数据放入markers
				switch (this.currentDisplayType) {
					case 'error':
						this.markers = [...(errormarkers[this.page])]
						return
					case 'warn':
						this.markers = [...(warnmarkers[this.page])]
						return
					case 'safe':
						this.markers = [...(safemarkers[this.page])]
						return
					case 'all':
						this.markers = [...(allmarkers[this.page]), ...(errormarkers[this.page]), ...(warnmarkers[this.page]), ...(safemarkers[this.page])]
						return
				}
			}
		},
		// 获取跑出危险区外的羊
		Inquire() {
			let array, marks
			if (this.currentDisplayType == 'error') {
				array = this.vertex
				marks = errormarkers
			} else if (this.currentDisplayType == 'warn') {
				array = this.warn
				marks = warnmarkers
			} else {
				array = this.safe
				marks = safemarkers
			}
			
			// 获取所有的羊 + 总页码
			getAllNum().then(res => {
			// request('/zq?page=0').then(res => {
				this.PageCount = Math.ceil(res.data.data.length / res.data.num)
				this.num = res.data.num
			}).finally(() => {
				this.getlist(array)
			})
		},
		// 关闭警告页面和报警
		findAlert() {
			this.show = false;
			this.showalert = true;
		},
		//语音报警和震动报警
		ScanAudio() {
			let music = uni.createInnerAudioContext();
			music.loop = true
			music.src = 'https://img.tukuppt.com/newpreview_music/09/00/13/5c8902563671136874.mp3';
			music.play()
			this.music = music
			uni.vibrateLong()
			let thime = setInterval(() => {
				uni.vibrateLong()
			}, 1000)
			console.log('开始',thime);
			this.thime = thime
		},
		// 停止音乐和震动
		closealert() {
			this.showalert = false
			setTimeout(() => {
				this.music.stop()
			}, 300)
			console.log("停止",this.thime);
			clearInterval(this.thime)
			this.thime = null
		},
		getPathing(obj) {
			// 暂存this---direction方法里面会用到
			let that = this
			// 获取当前地理位置
			this.qqmapsdk.direction({
				mode: 'driving',
				from: {
					latitude: 43.61122246320031,
					longitude: 87.50078201293945
				},
				to: {
					latitude: obj.latitude,
					longitude: obj.longitude
				},
				// 执行成功的回调
				success: function (res, data) {
					//坐标解压（返回的点串坐标，通过前向差分进行压缩）
					let dikm = Number(res.result.routes[0].distance) / 1000
					that.errlist.push({
						id: obj.id,
						_id: obj._id,
						dikm: dikm.toFixed(2)
					})
				}
			})
		},
		// 前往修改围栏页面
		updateFencing() {
			this.closealert()
			uni.navigateTo({
				url: '/pages/content/content'
			})
		}
	},
}
</script>

<style lang="scss">
.modalList{
	margin-top: 10px;
	.listItem:nth-child(2n-1){
		background-color: whitesmoke;
	}
}
.btn {
	position: fixed;
	top: 0;
	left: 0;
}

.alert {
	width: 600rpx;
	height: 500rpx;
}

.scroll-Y {
	width: 600rpx;
	height: 460rpx;
}

.scroll-view-item {
	height: 200rpx;
	font-size: 36rpx;

	.info {
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: space-between;
		line-height: 120rpx;

		image {
			width: 130rpx;
			height: 130rpx;
			border-radius: 50%;
		}
	}
}

.start {
	position: fixed;
	top: 0;
	right: 0;
	width: 100rpx;
	height: 100rpx;
	border-radius: 50%;
	background: aquamarine;
	text-align: center;
	line-height: 100rpx;
}
.closeWarn{
	position: fixed;
	top: 100rpx;
	right: 0;
	width: 70rpx;
	height: 100rpx;
	border-radius: 50%;
	background: red;
	text-align: center;
	line-height: 50rpx;
	padding: 0 15rpx
}
.text{
	position: absolute;
	color: red;
	left: 35%;
	top: 30%;
	font-size: 80rpx;
	font-family: fantasy;
}
</style>